//
//  ViewController.m
//  19-JSON
//
//  Created by GivenBmli on 16/8/9.
//  Copyright © 2016年 GivenBmli. All rights reserved.
//

#import "ViewController.h"
#import "BM-CollectionViewLayout.h"
#import "ContentTitle.h"
#import "TitleCollectionViewCell.h"
@interface ViewController ()<UICollectionViewDelegate , UICollectionViewDataSource, BM_LayoudDelget>
@property (weak, nonatomic) IBOutlet UICollectionView *myCollectionView;
@property (nonatomic , strong)NSMutableArray <ContentTitle *>*contentTitleArray;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    [self handleData];

}

- (void)handleData {
    self.contentTitleArray = [NSMutableArray array];
    //    JSON解析
    //    通过一个Data, 将JSON格式转换成OC认识的内容
    //    数组/字典
    //    获取JSON的Data
    NSString *dataPath = [[NSBundle mainBundle] pathForResource:@"FirstJSON" ofType:@"json"];
    NSData *jsonData = [NSData dataWithContentsOfFile:dataPath];
    //    json解析
    //   NSJSONSerialization
    NSError *error = nil;
    NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
    NSArray *list = jsonDic[@"tabs"][@"list"];
    for (NSDictionary *contentDic in list) {
        ContentTitle *contentTitle = [ContentTitle contentTitleWithDictionary:contentDic];
        NSLog(@"%@", contentTitle.title);
        [_contentTitleArray addObject:contentTitle];
    }
//    NSLog(@"%@",jsonDic[@"msg"]);
    
    //    NSLog(@"%@",self.myCollectionView.collectionViewLayout);
    BM_CollectionViewLayout *layout = (BM_CollectionViewLayout *)self.myCollectionView.collectionViewLayout;
    layout.delegate =self;

}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout widthForItemAtIndexPath:(NSIndexPath *)indexPath
                   height:(CGFloat)height {
    
    ContentTitle *contentTitle = _contentTitleArray[indexPath.row];
   CGRect newRect = [contentTitle.title boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, CGRectGetHeight(self.myCollectionView.bounds)) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:17]} context:nil];
    CGFloat width = ceilf (CGRectGetWidth(newRect));
    
       return width;

}


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return _contentTitleArray.count;
    
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    TitleCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"reuse" forIndexPath:indexPath];
    cell.contentTitle  =_contentTitleArray[indexPath.row];
    return cell;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
